-- Copyright © 2008-2012 Xianghar  <xian@zron.de>
-- All Rights Reserved.

if select(2,UnitClass("player")) ~= "MONK" then return end

if not XiTimers then 
    XiTimers = {}
    XiTimers.version = 300
end

XiTimers.timers = {}
XiTimers.nrOfTimers = 0
XiTimers.__index = XiTimers
XiTimers.updateInterval = 0

local inActiveAlpha = 0.4


local XiTimers = XiTimers
local Timers = XiTimers.timers
local _G = getfenv()

local incombat = false


local function FormatTime(frame, sec, format)
	local seconds = floor(sec)

 	if format == "blizz" then
		frame:SetFormattedText(SecondsToTimeAbbrev(sec))
    elseif format == "sec" then
        seconds = floor(sec+0.5)
        if seconds == 0 then seconds = "" end
        frame:SetFormattedText(tostring(seconds))
	else
		if(seconds <= 0) then
			frame:SetText("")
		elseif seconds < 600 then
			local d, h, m, s = ChatFrame_TimeBreakDown(seconds)
			frame:SetFormattedText("%01d:%02d", m, s)
		elseif(seconds < 3600) then
			local d, h, m, s = ChatFrame_TimeBreakDown(seconds);
			frame:SetFormattedText("%02d:%02d", m, s)
		else
			frame:SetText("1 hr+")
		end
	end
end


local function SetButtonTime(fontstring, sec)
    if sec > 600 then
        FormatTime(fontstring, sec, "blizz")
    elseif sec > 60 then
        FormatTime(fontstring, sec)
    else
        FormatTime(fontstring, sec, "sec")
    end
end


local nextUpdate = 0

function XiTimers.UpdateTimers(self,elapsed) 
    if XiTimers.updateInterval > 0 then nextUpdate = nextUpdate + elapsed end
    if nextUpdate >= XiTimers.updateInterval then
        nextUpdate = nextUpdate - XiTimers.updateInterval
        for i=1,XiTimers.nrOfTimers do
            if Timers[i].active and Timers[i].timer > 0 then Timers[i]:Update(elapsed) end
        end        
    end
end


function XiTimers:new(unclickable)
	local self = {}
	setmetatable(self, XiTimers)
	XiTimers.nrOfTimers = XiTimers.nrOfTimers + 1
    self.nr = XiTimers.nrOfTimers
	self.active = false
    self.unclickable = unclickable
	if unclickable then
        self.button = CreateFrame("CheckButton", "XiTimers_Timer"..XiTimers.nrOfTimers, UIParent, "XiTimersLiteUnsecureTemplate")
    else
        self.button = CreateFrame("CheckButton", "XiTimers_Timer"..XiTimers.nrOfTimers, UIParent, "XiTimersLiteTemplate")
		RegisterStateDriver(self.button, "petbattle", "[petbattle][overridebar][possessbar] active; none")
		RegisterStateDriver(self.button, "combat", "[combat] active; none")
		self.button:WrapScript(self.button, "OnAttributeChanged", [[
			if not self:GetAttribute("active") then return end
			if name == "state-petbattle" then
				if value == "active" then
					self:Hide()
				elseif not self:GetAttribute("HideOOC") then
					self:Show()
				end
			elseif name == "state-combat" then
				if value == "active" then
					self:Show()
				elseif self:GetAttribute("HideOOC") then
					self:Hide()
				end
			end
		]])
		
    end
	self.button:SetPoint("CENTER", UIParent, "CENTER")
	self.button.timer = self
	
	--for rActionButtonStyler
	self.button.action = 0 
    self.button:SetCheckedTexture(nil)
	self.button.SetCheckedTexture = function() end
    self.button.SetChecked = function() end
    self.button.GetChecked = function() return false end
    self.button.SetDisabledCheckedTexture = function() end
    
	self.button.unclickable = unclickable
	self.button.element = XiTimers.nrOfTimers
    
	
	self.timer = 0
    self.duration = 0
    self.barTimer = 0
    self.barDuration = 0
	self.timerBars = {}
	self.button.icons = {}
	self.button.flash = {}

	self.timerBar = CreateFrame("StatusBar", "XiTimers_TimerBar"..XiTimers.nrOfTimers, self.button, "XiTimersTimerBarTemplate")
    self.timerBar.background = _G["XiTimers_TimerBar"..XiTimers.nrOfTimers.."Background"]
    self.timerBar.time = _G["XiTimers_TimerBar"..XiTimers.nrOfTimers.."Time"]
    self.timerBar.icon = _G["XiTimers_TimerBar"..XiTimers.nrOfTimers.."Icon"]
    self.timerBar:SetPoint("TOP", self.button, "BOTTOM")
	self.button.icon = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Icon"]
	self.button.flash = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Flash"]
    if self.button.flash then
        local flash = self.button.flash
        flash.animation = self.button.flash:CreateAnimationGroup()
        flash.animation:SetLooping("NONE")
        flash.flashAnim = flash.animation:CreateAnimation()
        flash.flashAnim:SetDuration(15)
        flash.flashAnim.flash = flash
        flash.flashAnim:SetScript("OnPlay", function(self) self.flash:Show() end)
        flash.flashAnim:SetScript("OnFinished", function(self) self.flash:Hide() end)
        flash.flashAnim:SetScript("OnStop", function(self) self.flash:Hide() end)
        flash.flashAnim:SetScript("OnUpdate", function(self) self.flash:SetAlpha(BuffFrame.BuffAlphaValue) end)
	end
    if self.button.icon then
        local flash = self.button.icon
		flash.animation = self.button.flash:CreateAnimationGroup()
		flash.animation:SetLooping("NONE")
		flash.flashAnim = flash.animation:CreateAnimation()
		flash.flashAnim:SetDuration(15)
		flash.flashAnim.flash = flash
		flash.flashAnim:SetScript("OnPlay", function(self) self.flash:Show() end)
		flash.flashAnim:SetScript("OnUpdate", function(self) self.flash:SetAlpha(BuffFrame.BuffAlphaValue) end)
    end
	self:SetIconAlpha(self.button.icon, 0.4)
	
    self.timeColor = {r=1,g=1,b=1}
	self.button.icon:Show()
	self.timerBarPos = "BOTTOM"
	self.timeSpacing = 0
	self.spacing = 5
	self.timeStyle = "mm:ss"
    self.OOCAlpha = 1
	self.maxAlpha = 1
	self.warningMsg = nil
    self.warningSpell = nil
	self.expirationMsg = nil
	self.earlyExpirationMsg = nil
    self.warningIcon = nil
	self.events = {}
	self.button.count = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Count"]
	self.button.cooldown = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Cooldown"]
	self.button.miniIcon = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."MiniIcon"]
    self.button.miniIconFrame = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Mini"]
    self.button.bar = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."Bar"]
    self.button.hotkey = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."HotKey"]
    self.button.rangeCount = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."RangeCount"]
	self.button.normalTexture = _G["XiTimers_Timer"..XiTimers.nrOfTimers.."NormalTexture"]
	local frame = CreateFrame("Frame", nil, self.button)
    frame:Show()
    frame:SetAllPoints(self.button)
    self.button.time = frame:CreateFontString(self.button:GetName().."Time", 'OVERLAY')
    self.button.time:SetPoint("CENTER",0,1)
    self.button.time:SetFont("Fonts\\FRIZQT__.TTF", 17, "OUTLINE")
    frame:SetFrameLevel(frame:GetFrameLevel()+10)
    self.button.time:Hide()
    --self.button.cooldown:SetFrameLevel(self.button.cooldown:GetFrameLevel()-1)
    self.button.cooldown.noCooldownCount = true
    self.button.cooldown.noOCC = true
    self.rangeCheckCount = 0
    self.manaCheckCount = 0
	    
    self.animation = XiTimersAnimations:new(self.button)
	
	if not IsAddOnLoaded("rActionButtonStyler") then
		self:HideNormalTexture()
	else
		ActionButton_Update(self.button)
	end
    
	self.anchors = {}
	self.anchorchilds = {}
	
	--self.button:SetScript("OnDragStart", XiTimers.StartMoving)
	self.button:SetScript("OnDragStop", XiTimers.StopMoving)
    self.button:SetAttribute("_ondragstart", [[control:CallMethod("StartMove")]])
    --self.button:SetAttribute("_ondragstop", [[control:CallMethod("StopMoving")]])
    self.button.StartMove = XiTimers.StartMoving
    self.button.StopMove = XiTimers.StopMoving
	self.button:RegisterForDrag("LeftButton")
    
	table.insert(Timers, self)

    -- self.button:SetAttribute("_onattributechanged", [[ 
        -- if name=="state-invehicle" then
            -- if value == "show" and self:GetAttribute("active") then
                -- self:Show()
            -- else
                -- self:Hide()
            -- end
        -- end
        -- ]])

    self.button:Hide()
	return self
end

-- timer functions
local IsSpellInRange = IsSpellInRange
local IsUsableSpell = IsUsableSpell

function XiTimers:Update(elapsed)
	local timer = self.timer
    local button = self.button
    if not self.barTimerOnly then
		if timer > 0 then
			timer = timer - elapsed
			if timer <= 0 then
				self:Stop() 
			else
				if timer<10 and self.warningMsg then print(self.warningMsg)
					--self:PlayWarning(self.warningMsg, self.warningSpell, self.warningIcon)
					self.warningMsg = nil
				end
				if not self.hideTime then
					if not self.timerOnButton then
						if timer >= 600 then
							FormatTime(self.timerBar.time, timer, "blizz")
						else
							FormatTime(self.timerBar.time, timer, self.timeStyle)
						end
					else
						SetButtonTime(button.time, timer)
					end
					if self.visibleTimerBars and not self.timerOnButton then
						self.timerBar:SetValue(timer)
					end
				end
				if not self.isAnimating and timer <= 10 and timer > 0 then
					self.isAnimating = true
					if not self.dontFlash then
						if self.flashRed and self.button.flash then
							self.button.flash.animation:Play()
						elseif self.button.icon then
							self.button.icon.animation:Play()
						end
					end
				end 
				if self.procFlash and timer > 0 and self.bar then
					button.bar:SetValue(self.bar - mod(timer, self.bar))
					button.bar:Show()
				end
			end
		end
    end
    
    if self.barTimer > 0 then
        self.barTimer = self.barTimer - elapsed
        button.bar:SetValue(self.barTimer)        
    end
	
	self.timer = timer
    
    --self.button.icon:SetVertexColor(1,1,1)
    --if not self.unclickable then self.button.miniIcon:SetVertexColor(1,1,1) end
   --[[ if self.RangeCheck then
        self.RangeCheckCount = self.RangeCheckCount + 1
        if self.RangeCheckCount > 8 then
            self.RangeCheckCount = 0
            self.outofrange = IsSpellInRange(self.RangeCheck) == 0
            if self.outofrange then
                self.button.icon:SetVertexColor(1,0,0)
            else
                self.button.icon:SetVertexColor(1,1,1)
            end
        end
    end
    
    if self.ManaCheck then
        self.ManaCheckCount = self.ManaCheckCount + 1
        if self.ManaCheckCount > 8 then
            self.ManaCheckCount = 0
            local _,nomana = IsUsableSpell(self.ManaCheck)
            if nomana then
                if self.ManaCheckMini then
                    self.button.miniIcon:SetVertexColor(0.5,0.5,1)
                else
                    self.button.icon:SetVertexColor(0.5,0.5,1)
                end
            else
                if self.ManaCheckMini then
                    self.button.miniIcon:SetVertexColor(1,1,1)
                else
                    if self.outofrange then
                        self.button.icon:SetVertexColor(1,0,0)
                    else
                        self.button.icon:SetVertexColor(1,1,1)
                    end
                end
            end
        end
    end]]
    
    --!!
end


function XiTimers:Activate()
	self.active = true
	for _,event in pairs(self.events) do
		self.button:RegisterEvent(event)
	end
	if not self.hideInactive and (not self.HideOOC or InCombatLockdown()) then
        self.button:Show()        
    end
	self.button:SetAttribute("active", true)
    if self.rangeCheck or self.manaCheck then
		self:AddRangeCheck()
	end
end

function XiTimers:Deactivate()
	self.active = false
	for _,event in pairs(self.events) do
		self.button:UnregisterEvent(event)
	end
	self.button:Hide()
    self.button:SetAttribute("active", false)
	self:RemoveRangeCheck()
end

function XiTimers:Start(time, duration)
	duration = duration or time
    self.duration = duration
	local timerbar = self.timerBar
	self.timer = time
	FormatTime(timerbar.time, time, self.timeStyle)
    FormatTime(self.button.time, time, self.timeStyle)
	timerbar:SetMinMaxValues(0, duration)

	if self.visibleTimerBars and not self.timerOnButton then
		timerbar:SetValue(time)
	end
	if not self.dontAlpha then self:SetIconAlpha(self.button.icon, self.maxAlpha) end
    if self.reverseAlpha then self:SetIconAlpha(self.button.icon, 0.4) end
	if not self.hideTime then
		if not self.timerOnButton then
			self.button.time:Hide()
			self:ShowTimerBar()
		else
			self:HideTimerBar()
			self.button.time:Show()
			self.button.time:SetTextColor(self.timeColor.r,self.timeColor.g,self.timeColor.b)
		end
	else
		self.button.time:Hide()
		self:HideTimerBar()
	end
	if (self.showCooldown or self.timerOnButton) and not self.prohibitCooldown then
		CooldownFrame_SetTimer(self.button.cooldown, GetTime()-duration+time, duration, 1)
	else
		self.button.cooldown:Hide()
	end
	if self.procFlash then 
		self.button.bar:Show()
		self.button.bar:SetValue(0)		
	elseif self.barTimer <= 0 then
		self.button.bar:Hide()
	end
    self.button.flash.animation:Stop()
    self.isAnimating = false
    --self.flashRed = XiTimers.flashRed
    --self.button.bar:SetValue(0)
    self:SetTimerBarPos(self.timerBarPos, true)
    if self.hideInactive then
        self.button:Show()
    end
end

function XiTimers:Stop()	
	local timerbar = self.timerBar
    if not self.stopQuiet then
        if self.timer>1 then
            if self.earlyExpirationMsg then
                self:PlayWarning(self.earlyExpirationMsg, self.warningSpell, self.warningIcon)
                self.earlyExpirationMsg = nil
            end
        elseif self.expirationMsg then print(self.expirationMsg)
           -- self:PlayWarning(self.expirationMsg, self.warningSpell, self.warningIcon)
            self.expirationMsg = nil
        end
        if self.StopPulse then
            self.animation:SetTexture(self.button.icon:GetTexture())
            self.animation:Play()
        end
    end
    self.stopQuiet = false
	timerbar.time:SetText("")
	if self.visibleTimerBars then		
		timerbar:SetValue(0)
	end
    self:HideTimerBar(timer)
    self.button.time:Hide()
    self.button.cooldown:Hide()
    if not self.dontAlpha then self:SetIconAlpha(self.button.icon, 0.4) end
    if self.reverseAlpha then self:SetIconAlpha(self.button.icon,self.maxAlpha) end
    self.button.bar:Hide()
    self:SetTimerBarPos(self.timerBarPos, true)
    if self.hideInactive then
        self.button:Hide()
    end
    self:SetOutOfRange(false)
	self.timer = 0
end


function XiTimers:StartBarTimer(time, duration)
    self.barDuration = duration or time
    self.barTimer = time
    self.button.bar:SetMinMaxValues(0, duration)
    self.button.bar:SetValue(time)
    self.button.bar:Show()
end

function XiTimers:StopBarTimer()
    self.barTimer = 0
    self.button.bar:SetValue(0)
    self.button.bar:Hide()
end


function XiTimers:SetOutOfRange(outOfRange)
    self.outOfRange = outOfRange
    self:UpdateButtonColor()
end

function XiTimers:SetOutOfMane(outOfMana)
    self.outOfMana = outOfMana
    self:UpdateButtonColor()
end

function XiTimers:UpdateButtonColor()
    if self.outOfRange then
        self.button.icon:SetVertexColor(1,0,0)
    elseif self.outOfMana then
        self.button.icon:SetVertexColor(0.5,0.5,2)
    else
        self.button.icon:SetVertexColor(1,1,1)
    end
end

function XiTimers:StartMoving()
    if self.timer.locked then return end
	if self.anchorframe and not self.timer.savePos then
		self.anchorframe:StartMoving()
	else
		self:StartMoving() 
	end
end

function XiTimers:StopMoving()
	if self.anchorframe and not self.timer.savePos then
		self.anchorframe:StopMovingOrSizing()
	else
		self:StopMovingOrSizing()
	end
    if XiTimers.SaveFramePositions then XiTimers.SaveFramePositions() end
    self.timer:SetTimerBarPos(self.timer.timerBarPos, true)
end

function XiTimers:SetIconAlpha(icon, alpha)
    if icon then
        icon:SetAlpha(alpha)
    end
end

function XiTimers:SetAlpha(alpha)
    self.button:SetAlpha(alpha)
end

function XiTimers:HideTimerBar()
	self.timerBar.background:Hide()
    self.timerBar.background:SetValue(0)
    ---self.timerBars[nr].icon:Hide()
    self.timerBar:Hide()
end

function XiTimers:ShowTimerBar()
    self.timerBar:Show()
	if self.visibleTimerBars then
        self.timerBar.background:Show()
        self.timerBar.background:SetValue(1)
    end
end

-- display functions

function XiTimers:SetTimerBarPos(side, notReanchor)
	self.timerBarPos = side
	
	local TimerBar = self.timerBar
		
	TimerBar:ClearAllPoints()
    TimerBar.icon:ClearAllPoints()
	
    if side == "RIGHT" then
        TimerBar.icon:SetPoint("LEFT", TimerBar, "RIGHT", -4, 0)
    else
        TimerBar.icon:SetPoint("RIGHT", TimerBar, "LEFT", 4, 0)
    end
    local activetimers = 1
	if side == "LEFT" then
		TimerBar:SetPoint("RIGHT", self.button, "LEFT", -self.timeSpacing, TimerBar:GetHeight()*TimerBar:GetEffectiveScale()/2)
	elseif side == "RIGHT" then
		TimerBar:SetPoint("LEFT", self.button, "RIGHT", self.timeSpacing, TimerBar:GetHeight()*TimerBar:GetEffectiveScale()/2)
	elseif side == "TOP" then
		TimerBar:SetPoint("BOTTOM", self.button, "TOP", 0, self.timeSpacing)
	elseif side == "BOTTOM" then
   		TimerBar:SetPoint("TOP", self.button, "BOTTOM", 0, -self.timeSpacing)
	end
	if not InCombatLockdown() and not notReanchor then self:Reanchor() end
end

function XiTimers:GetBorder(side)
	local timerBarPos = self.timerBarPos
	if side == "TOP" and timerBarPos == "TOP" or side == "BOTTOM" and timerBarPos == "BOTTOM" then
        local height = self.timerBar:GetHeight()*self.timerBar:GetEffectiveScale()        
		return self.timerOnButton and 0 or self.timeSpacing + height
	elseif ((side == "LEFT" and timerBarPos == "LEFT" or side == "RIGHT" and timerBarPos == "RIGHT") and not self.timerOnButton)
    then
		return (self.timeSpacing + self.timerBar:GetWidth()*self.timerBar:GetEffectiveScale())
	end
	return 0
end


function XiTimers:SetWidth(width)
	self.button:SetWidth(width)
end

function XiTimers:SetHeight(height)
	self.button:SetHeight(height)
end

function XiTimers:SetFont(font)
    local _,height = self.timerBar.time:GetFont()
    self.timerBar.time:SetFont(font, height)
    local _,height = self.button.time:GetFont()
    self.button.time:SetFont(font, height, "OUTLINE")
end

function XiTimers:SetTimeHeight(height)
	self.timerBar:SetHeight(height)
	local font = self.timerBar.time:GetFont()
	self.timerBar.time:SetFont(font, height)
	self:Reanchor()
end

function XiTimers:SetTimeWidth(width)
	self.timerBar:SetWidth(width)
	self.timerBar.time:SetWidth(width)
	self:Reanchor()
end

function XiTimers:SetScale(scale)
	self.button:SetScale(scale)
	self:SetTimerBarPos(self.timerBarPos)
	--self:Reanchor()
end

function XiTimers:SetBarTexture(texture)
    self.timerBar:SetStatusBarTexture(texture)
    self.timerBar.background:SetStatusBarTexture(texture)
end

function XiTimers:SetBarColor(r,g,b)
    self.timerBar:SetStatusBarColor(r,g,b, 1.0)
    self.timerBar.background:SetStatusBarColor(r,g,b,0.4)
end


--allowed position combinations are: CENTER/CENTER, LEFT/RIGHT, RIGHT/LEFT, TOP/BOTTOM, BOTTOM/TOP

local CounterPositions = {
	CENTER = "CENTER",
	LEFT = "RIGHT",
	RIGHT = "LEFT",
	TOP = "BOTTOM", 
	BOTTOM = "TOP",
    TOPLEFT = "BOTTOM",
    TOPRIGHT = "BOTTOM",
}

local DirectionXMult = {
	CENTER = 0,
	LEFT = 1,
	RIGHT = -1,
	TOP = 0,
	BOTTOM = 0,
    TOPRIGHT = -1,
    TOPLEFT = 1,
}

local DirectionYMult = {
	CENTER = 0,
	LEFT = 0,
	RIGHT = 0,
	TOP = -1,
	BOTTOM = -1,
    TOPRIGHT = -1,
    TOPLEFT = -1,
}


function XiTimers:SetPoint(pos, relframe, relpos, halfspace)
	local relborder = 0
	if relframe.button then 
		if not relpos then relborder = relframe:GetBorder(CounterPositions[pos])
        else relborder = relframe:GetBorder(relpos) end
		relframe = relframe.button
	end
	local borderx = self:GetBorder(pos)+relborder
    local bordery = borderx
    --hack for anchoring TOPRIGHT or TOPLEFT to BOTTOM, maybe change it account for all anchors someday if needed
    if relpos == "BOTTOM" then borderx = 0 end
	self.button:ClearAllPoints()
    if not relpos then relpos = CounterPositions[pos] end
    local spacingx = self.spacing
    if halfspace then spacingx = spacingx / 2 end
    local spacingy = self.spacing
	self.button:SetPoint(pos, relframe, relpos, (spacingx+borderx)*DirectionXMult[pos], (spacingy+bordery)*DirectionYMult[pos])
end

-- anchors this timer to another
function XiTimers:Anchor(timer, point, relpoint, halfspace)
	table.insert(self.anchors, {timer = timer, point = point, relpoint = relpoint, halfspace = halfspace})
	table.insert(timer.anchorchilds, self)
	self:SetPoint(point, timer, relpoint, halfspace) 
end

-- updates the positions of all frames anchored to this timer
function XiTimers:Reanchor()
	for _, anchor in pairs(self.anchors) do
		self:SetPoint(anchor.point, anchor.timer, anchor.relpoint)
	end
	for _, anchorchild in pairs(self.anchorchilds) do
		anchorchild:Reanchor()
	end
end

function XiTimers:ClearAnchors()
	self.anchors = {}
	self.anchorchilds = {}
end

function XiTimers:SetSpacing(spacing)
	self.spacing = spacing
	self:Reanchor()
end

function XiTimers:SetTimeSpacing(spacing)
	self.timeSpacing = spacing
	self:SetTimerBarPos(self.timerBarPos)
	--self:Reanchor()
end


function XiTimers:Show()
    self.button:Show()
	self:ShowTimerBar()
    --[[for i=1,self.nrOfTimers do
        if self.timers[i] > 0 then
            self:ShowTimerBar(i)
        end
    end]]
end

function XiTimers:Hide()
    self.button:Hide()
	self:HideTimerBar()
   --[[ for i=1,self.nrOfTimers do
        if self.timers[i] > 0 then
            self:HideTimerBar(i)
        end
    end]]
end

function XiTimers:HideNormalTexture()
	self.button.normalTexture:SetTexture(1,1,1,0)		
end


--Out-of-combat-Fader

local oocframe = CreateFrame("Frame", "XiTimersOOCFaderFrame")
oocframe:RegisterEvent("PLAYER_REGEN_ENABLED")
oocframe:RegisterEvent("PLAYER_REGEN_DISABLED")


function XiTimers.invokeOOCFader()
    XiTimers.OOCFaderEvent(nil, (InCombatLockdown() and "PLAYER_REGEN_DISABLED") or "PLAYER_REGEN_ENABLED")
end

XiTimers.OOCFaderEvent = function(self, event)
    if event == "PLAYER_REGEN_ENABLED" then
        incombat = false
        for _,timer in pairs(XiTimers.timers) do
            if timer.active and timer.unclickable and timer.HideOOC then
                timer:Hide()
            end
            timer.button:SetAlpha(timer.OOCAlpha)
        end
    elseif event == "PLAYER_REGEN_DISABLED" then
        incombat = true
        for _,timer in pairs(XiTimers.timers, true) do
            if timer.active and timer.unclickable and timer.HideOOC and not timer.hideInactive then
                timer:Show()
            end
            timer.button:SetAlpha(1)
        end        
    end
end

oocframe:SetScript("OnEvent", XiTimers.OOCFaderEvent)

local rangeManaFrame = CreateFrame("Frame")
local lastRangeUpdate = 0
local rangeManaCheckFrames = {}

local function rangeManaUpdate(self, elapsed)
	lastRangeUpdate = lastRangeUpdate + 1
	if lastRangeUpdate > #rangeManaCheckFrames then lastRangeUpdate = 1 end
	local timer = rangeManaCheckFrames[lastRangeUpdate]
	if not timer then return end
    if timer.rangeCheck then
        --self.rangeCheckCount = self.rangeCheckCount + 1
        --if self.rangeCheckCount > 8 then
           -- self.rangeCheckCount = 0
            timer.outofrange = IsSpellInRange(timer.rangeCheck, "target") == 0
            if timer.outofrange then
                timer.button.icon:SetVertexColor(1,0,0)
            else
                timer.button.icon:SetVertexColor(1,1,1)
            end
       -- end
    end
    
    if timer.manaCheck then
        --self.manaCheckCount = self.manaCheckCount + 1
        --if self.manaCheckCount > 8 then
            --self.manaCheckCount = 0
            local _,nomana = IsUsableSpell(timer.manaCheck)
			if nomana then
                timer.button.icon:SetVertexColor(0.5,0.5,1)
            else
                if timer.outofrange then
                    timer.button.icon:SetVertexColor(1,0,0)
                else
                    timer.button.icon:SetVertexColor(1,1,1)
                end
            end
        --end
    end
end

rangeManaFrame:SetScript("OnUpdate", rangeManaUpdate)
rangeManaFrame:Show()

function XiTimers.AddRangeCheck(self)
	local isIn = false
	for i=1,#rangeManaCheckFrames do
		if rangeManaCheckFrames[i] == self then isIn = true end
	end
	if not isIn then table.insert(rangeManaCheckFrames, self) end
end

function XiTimers.RemoveRangeCheck(self)
	for i=1,#rangeManaCheckFrames do
		if rangeManaCheckFrames[i] and rangeManaCheckFrames[i] == self then
			table.remove(rangeManaCheckFrames,i)
			i = i - 1
		end
	end
end